package wan.moneybook.setup;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.Properties;

import wan.moneybook.bean.Account;
import wan.moneybook.bean.Type;
import wan.moneybook.sql.SqlMapper;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;

public class SetupTable {
	private SqlMapClient sqlMap = SqlMapper.getInstance();

	public void setAll() throws SQLException,IOException {
		//dropTable();
		setTable();
		setGuest();
		setCategory();
		setCard();
	}

	public void dropTable() throws SQLException {
		sqlMap.delete("dropRecord");
		sqlMap.delete("dropCategory");
		sqlMap.delete("dropCard");
		sqlMap.delete("dropAccount");
	}

	public void setTable() throws SQLException {
		sqlMap.insert("createAccount");
		sqlMap.insert("createCategory");
		sqlMap.insert("createCard");
		sqlMap.insert("createRecord");
		System.out.println("CREATE TABLE Succeed.");
	}

	public void setGuest() throws SQLException {
		sqlMap.insert("addAccount", new Account("guest","guest"));
		System.out.println("Guest Account Enabled.");
	}

	public void setCategory() throws SQLException,IOException {
		sqlMap.delete("removeAllCategory");
		String resource = "wan/moneybook/setup/category.properties";
		String sql = "addCategory";
		insertData(resource,sql);
		System.out.println("Category Data Init");
	}

	public void setCard() throws SQLException,IOException {
		sqlMap.delete("removeAllCard");
		String resource = "wan/moneybook/setup/card.properties";
		String sql = "addCard";
		insertData(resource,sql);
		System.out.println("Card Data Init");
	}

	public void insertData(String resource, String sql) throws SQLException,IOException {
		Reader reader = Resources.getResourceAsReader(resource);
		Properties prop = new Properties();
		prop.load(reader);
		Type type = new Type();
		for(Object key : prop.keySet()) {
			type.setType(Integer.parseInt((String)key));
			type.setName((String)prop.get(key));
			sqlMap.insert(sql, type);
		}
		reader.close();
	}
}
